package com.k8.rpc.invoke.invoker;

import com.k8.rpc.exchange.Exchange;
import com.k8.rpc.invoke.Invoker;
import com.k8.rpc.invoke.invocation.Invocation;
import com.k8.rpc.result.Result;
import com.k8.rpc.url.URL;

import java.lang.reflect.Method;

/**
 * @Author: k8
 * @CreateTime: 2025-03-26
 * @Version: 1.0
 */
public class ConsumerInvoker<T> implements Invoker<T> {
    private volatile boolean available = true;
    private final Class<T> interfaceClazz;
    private URL url;
    private final Exchange exchange;

    public ConsumerInvoker(Class<T> interfaceClazz, URL url, Exchange exchange) {
        assert interfaceClazz != null;
        assert url != null;
        assert exchange != null;
        this.interfaceClazz = interfaceClazz;
        this.url = url;
        this.exchange = exchange;
    }

    //这里invoke已经异步转同步了
    @Override
    public Result<?> invoke(Invocation invocation) throws Throwable {
        return exchange.call(invocation);
    }

    /**
     * 进行Rpc调用时一定要遵从{@link com.k8.common.util.ClassUtil#getMethodToString(Method)} 生成对应的MethodKey对应的Value
     */

    @Override
    public URL getUrl() {
        return this.url;
    }

    @Override
    public boolean isAvailable() {
        return this.available;
    }

    public void setAvailable(boolean b) {
        this.available = b;
    }

    @Override
    public void destroy() {

    }

    @Override
    public Class<T> getInterface() {
        return this.interfaceClazz;
    }

    @Override
    public T getTarget() {
        throw new IllegalStateException("Just invoker of provider need target");
    }
}
